import { Form, Input, Button } from 'antd'
import React, { useState } from 'react'
import './index.scss'
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom'
import { login } from "../../api/common"
import { setItem } from "../../utils/storage"

const Login = () => {

  const navigate = useNavigate()
  const [loading, setLoading] = useState(false)

  const onFinish = async (values) => {
    setLoading(true)
    const data = await login(values).finally(() => {
      setLoading(false)
    })
    setItem('user', data)
    navigate('/')
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <div className="login-container">
      <Form
        labelCol={{ span: 0 }}
        wrapperCol={{ span: 24 }}
        initialValues={{
          username: "admin",
          password: "123456",
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
        className="login-form"
      >
        <div className="login-form-header">
          <img className="login-logo" src="/logo192.png" alt="" />
          <div>电商后台管理系统</div>
        </div>
        <Form.Item
          label="用户名"
          name="username"
          rules={[{ required: true, message: '请输入用户名' }]}
        >
          <Input prefix={<UserOutlined />} />
        </Form.Item>
        <Form.Item
          label="密码"
          name="password"
          rules={[{ required: true, message: '请输入密码' }]}
        >
          <Input.Password prefix={<LockOutlined />} />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" block loading={loading}>
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}

export default Login
